/*
 * @Author: kanglang
 * @Date: 2020-11-24 13:25:37
 * @LastEditors: 汪滔
 * @LastEditTime: 2021-06-04 15:23:34
 * @Description: 异步存储方法
 * 未回调方法 调用时需要async await
 */
import AsyncStorage from '@react-native-community/async-storage';
import msg from './msg';
import cache from './cache';

export default {
  // 存储字符串
  setItem: async (key, value) => {
    try {
      await AsyncStorage.setItem(key, JSON.stringify(value));
    } catch (e) {
      msg.emit('app:tip', { text: '保存失败' });
    }
  },
  // 获取字符串
  getItem: async (key) => {
    try {
      const value = await AsyncStorage.getItem(key);
      return JSON.parse(value);
    } catch (e) {
      msg.emit('app:tip', { text: '取值失败' });
    }
  },
  // 存储token
  setToken: async (value) => {
    try {
      await AsyncStorage.setItem(cache.APP_TOKEN, value);
    } catch (e) {
      msg.emit('app:tip', { text: 'token保存失败' });
    }
  },
  // 获取token
  getToken: async () => {
    try {
      const value = await AsyncStorage.getItem(cache.APP_TOKEN);
      return value;
    } catch (e) {
      msg.emit('app:tip', { text: 'Token获取失败' });
    }
  },

  // 获取登录信息
  getUserInfo: async () => {
    try {
      const value = await AsyncStorage.getItem(cache.USER_INFO);
      return JSON.parse(value);
    } catch (e) {
      msg.emit('app:tip', { text: '用户信息获取失败' });
    }
  },
  // 清除Token
  removeToken: async () => {
    try {
      await AsyncStorage.removeItem(cache.APP_TOKEN);
    } catch (e) {
      console.log(e);
    }
  },
  // 清除登录相关信息
  removeUserInfo: async () => {
    try {
      await AsyncStorage.removeItem(cache.USER_INFO);
    } catch (e) {
      console.log(e);
    }
  },
  // 清除回调
  removeItem: async (key) => {
    try {
      await AsyncStorage.removeItem(key);
    } catch (e) {
      console.log(e);
    }
  },
  // 获取全部key
  getAllKeys: async () => {
    let keys = [];
    try {
      keys = await AsyncStorage.getAllKeys();
    } catch (e) {
      console.log(e);
    }
    console.log(keys);
    return keys;
  },
};
